package com.ruoyi.training.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.training.dto.payment.PreInvoiceCorrelationInfo;
import com.ruoyi.training.dto.payment.PreInvoiceRefundDto;
import com.ruoyi.training.dto.registration.RegistrationDto;
import com.ruoyi.training.mapper.RegistrationMapper;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.payment.PreInvoiceVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.mapper.PreInvoiceMapper;
import com.ruoyi.training.domain.PreInvoice;
import com.ruoyi.training.service.IPreInvoiceService;

/**
 * 预开票Service业务层处理
 *
 * @author hcc
 * @date 2025-09-29
 */
@Service
public class PreInvoiceServiceImpl implements IPreInvoiceService
{
    @Autowired
    private PreInvoiceMapper preInvoiceMapper;

    @Autowired
    private RegistrationMapper registrationMapper;
    /**
     * 查询预开票
     *
     * @param preInvoiceId 预开票主键
     * @return 预开票
     */
    @Override
    public PreInvoice selectPreInvoiceByPreInvoiceId(String preInvoiceId)
    {
        return preInvoiceMapper.selectPreInvoiceByPreInvoiceId(preInvoiceId);
    }

    /**
     * 查询预开票列表
     *
     * @param preInvoice 预开票
     * @return 预开票
     */
    @Override
    public List<PreInvoice> selectPreInvoiceList(PreInvoice preInvoice)
    {
        return preInvoiceMapper.selectPreInvoiceList(preInvoice);
    }

    /**
     * 新增预开票
     *
     * @param preInvoice 预开票
     * @return 结果
     */
    @Override
    public int insertPreInvoice(PreInvoice preInvoice)
    {
        preInvoice.setCreateTime(DateUtils.getNowDate());
        preInvoice.setPreDelFlag("0");
        preInvoice.setPreInvoiceId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
        return preInvoiceMapper.insertPreInvoice(preInvoice);
    }

    /**
     * 修改预开票
     *
     * @param preInvoice 预开票
     * @return 结果
     */
    @Override
    public int updatePreInvoice(PreInvoice preInvoice)
    {
        preInvoice.setUpdateTime(DateUtils.getNowDate());
        return preInvoiceMapper.updatePreInvoice(preInvoice);
    }

    /**
     * 批量删除预开票
     *
     * @param preInvoiceIds 需要删除的预开票主键
     * @return 结果
     */
    @Override
    public int deletePreInvoiceByPreInvoiceIds(String[] preInvoiceIds)
    {
        return preInvoiceMapper.deletePreInvoiceByPreInvoiceIds(preInvoiceIds);
    }

    /**
     * 删除预开票信息
     *
     * @param preInvoiceId 预开票主键
     * @return 结果
     */
    @Override
    public int deletePreInvoiceByPreInvoiceId(String preInvoiceId)
    {
        return preInvoiceMapper.deletePreInvoiceByPreInvoiceId(preInvoiceId);
    }

    /**
     * 批量删除预开票信息
     */
    @Override
    public int removePreInvoices(String[] preInvoiceIds) {
        return preInvoiceMapper.removePreInvoices(preInvoiceIds);
    }

    /**
     * 预开票关联报名信息
     */
    @Override
    public int associationRegistration(PreInvoice preInvoice) {
        PreInvoice preInvoiceDb = preInvoiceMapper.selectPreInvoiceByPreInvoiceId(preInvoice.getPreInvoiceId());
        if (StringUtils.isNotEmpty(preInvoice.getRegistrationId())) {
            BigDecimal totalCost = BigDecimal.ZERO;
            StringBuffer information = new StringBuffer();
            String[] split = preInvoice.getRegistrationId().split(",");
            // 处理学员姓名拼接：最后一个不追加分隔符
            for (int i = 0; i < split.length; i++) {
                String registrationId = split[i];
                RegistrationDto registrationDto = registrationMapper.selectRegistrationByRegistrationId(registrationId);
                if (registrationDto == null) {
                    continue;
                }
                // 非第一个元素前加分隔符
                if (i > 0) {
                    information.append(";");
                }
                information.append(registrationDto.getStudentName());
                // 累加项目费用
                if (StringUtils.isNotEmpty(registrationDto.getProjectSum())){
                    BigDecimal projectSum = new BigDecimal(registrationDto.getProjectSum());
                    totalCost = totalCost.add(projectSum);
                }else {
                    BigDecimal projectSum = BigDecimal.ZERO;
                    totalCost = totalCost.add(projectSum);
                }
            }
            // 设置关联金额
            preInvoice.setPreCorrelationAmount(totalCost.stripTrailingZeros().toPlainString());
            preInvoice.setPreCorrelation(information.toString());
            // 计算余额
            BigDecimal preInvoiceAmount = new BigDecimal(preInvoiceDb.getPreInvoiceAmount());
            BigDecimal balance = preInvoiceAmount.subtract(totalCost);
            // 处理余额格式：去除末尾0，避免科学计数法
            String balanceStr = balance.stripTrailingZeros().toPlainString();
            // 设置最终字段
            preInvoice.setPreUnassociated(balanceStr);
            preInvoice.setUpdateTime(DateUtils.getNowDate());
            preInvoice.setUpdateBy(SecurityUtils.getUsername());
        }
        return preInvoiceMapper.updatePreInvoice(preInvoice);
    }

    /**
     * 查询预开票列表
     */
    @Override
    public List<PreInvoice> selectList(PreInvoiceVo preInvoiceVo) {
        return preInvoiceMapper.selectList(preInvoiceVo);
    }

    /**
     * 获取预开票退换票详细信息
     */
    @Override
    public PreInvoiceRefundDto getRefundInfo(String preInvoiceId) {
        PreInvoiceRefundDto preInvoiceRefundDto = new PreInvoiceRefundDto();
        PreInvoice preInvoice = preInvoiceMapper.selectPreInvoiceByPreInvoiceId(preInvoiceId);
        if (StringUtils.isNotNull(preInvoice)){
            BeanUtils.copyProperties(preInvoice,preInvoiceRefundDto);
            if (StringUtils.isNotEmpty(preInvoice.getRegistrationId())){
                String[] split = preInvoice.getRegistrationId().split(",");
                RegistrationDto registrationDto = registrationMapper.selectRegistrationByRegistrationId(split[0]);
                if (StringUtils.isNotNull(registrationDto)){
                    BeanUtils.copyProperties(registrationDto,preInvoiceRefundDto);
                }
            }
        }
        return preInvoiceRefundDto;
    }

    /**
     * 预开票关联信息
     */
    @Override
    public PreInvoiceCorrelationInfo getCorrelationInfo(String preInvoiceId) {
        PreInvoiceCorrelationInfo preInvoiceCorrelationInfo = new PreInvoiceCorrelationInfo();
        PreInvoice preInvoice = preInvoiceMapper.selectPreInvoiceByPreInvoiceId(preInvoiceId);
        if (StringUtils.isNotNull(preInvoice)){
            BeanUtils.copyProperties(preInvoice,preInvoiceCorrelationInfo);
            List<RegistrationDto> registrationDtoList = new ArrayList<>();
            if (StringUtils.isNotEmpty(preInvoice.getRegistrationId())){
                String[] split = preInvoice.getRegistrationId().split(",");
                for (String registrationId : split) {
                    RegistrationDto registrationDto = registrationMapper.selectRegistrationByRegistrationId(registrationId);
                    registrationDtoList.add(registrationDto);
                }
            }
            preInvoiceCorrelationInfo.setRegistrationDtoList(registrationDtoList);
        }
        return preInvoiceCorrelationInfo;
    }
}
